package rdr.maps.ui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import rdr.geo.entities.Coordinate;
import rdr.geo.map2d.tiles.Tile;
import rdr.geo.map2d.tiles.TileManager;

public class PicturePanel extends JPanel {

    private Cursor defaultCursor;

    private boolean mousePressed = false;
    private TileManager tileManager;

    public PicturePanel() {
        this.addMouseListener(new java.awt.event.MouseAdapter() {

            @Override
            public void mousePressed(java.awt.event.MouseEvent e) {
                picturePanelMousePressed(e);
                super.mousePressed(e);
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                picturePanelMouseReleased(e);
                super.mouseReleased(e);
            }
        });

        tileManager = new TileManager();
        //tileManager.loadTiles("C:\\Documents and Settings\\ruanor\\My Documents\\maps\\");
        
        try
        {
        tileManager.loadTiles("data/maps");
        }
        catch(Exception e)
        {
            
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        if (tileManager == null) {
            return;
        }

        Graphics2D g2 = (Graphics2D) g;

        //paint background
        g2.setPaint(Color.black);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());

        //paint tiles
        for (Tile tile : tileManager.getTiles()) {
            
            // get tile coordinates
            int x = (int) tile.getCoordinate().getLat().getValue();
            int y = (int) tile.getCoordinate().getLon().getValue();
            g.drawImage(tile.getImage(), (int) x, (int) y, 500, 250, null);
        }

        //paint selector
        if (mousePressed) {
            g2.setPaint(Color.red);
            g.fillRect(this.getWidth() / 2, this.getHeight() / 2, 10, 10);
        }
    }

    private void picturePanelMousePressed(MouseEvent evt) {
        mousePressed = true;
        defaultCursor = this.getCursor();
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        this.repaint();
    }

    private void picturePanelMouseReleased(MouseEvent e) {
        mousePressed = false;
        setCursor(defaultCursor);
        this.repaint();
    }
}
